
import Image, math

class GrabCell:
  def __init__(self):
    pass

  def action(self, fn):
    "fn: image file name"
    #im = Image.open("grab_test.png", 'r')
    im = Image.open(fn, 'r')
    #print im.format, im.size, im.mode

    pix_flag = 0
    rect_x = list()
    PITCH, HEIGHT = im.size

    # detect X
    for x in range(PITCH):
      # get left
      if pix_flag==0:
        for y in range(HEIGHT):
          #print "(", x, y, "): ", im.getpixel((x,y))
          pxl = im.getpixel((x,y))
          if pxl!=(255, 255, 255, 255):
            pix_flag = 1
            rect_x.append(x)
            break
      else:
        for y in range(HEIGHT):
          pxl = im.getpixel((x,y))
          if pxl!=(255, 255, 255, 255):
            break
        else:
          # all white pixel
          rect_x.append(x)
          pix_flag = 0

    #print rect_x
    # [4, 16, 20, 29, 31, 40, 42, 51, 54, 56, 58, 67, 69, 78]

    # count non-white point number
    nwp_list = list()
    for i in range(0, len(rect_x), 2):
      nwp_num = 0
      (left, right) = (rect_x[i], rect_x[i+1])
      #print "processing bar: (%d, %d)"%(left, right)
      for x in range(left, right):
        for y in range(HEIGHT):
          pxl = im.getpixel((x,y))
          if pxl!=(255, 255, 255, 255):
            nwp_num += math.log(y + 1)
      nwp_list.append(nwp_num)

    #print nwp_list
    return nwp_list
    del im

if __name__=='__main__':
  fo = file('result.txt', 'w')
  gc = GrabCell()
  fl = ("gp233326,3.png",
        "gp376587,3.png",
        "gp495084,3.png",
        "gp509021,3.png",
        "gp1000396784,3.png")
  for x in fl:
    #print "\n\n\n\n"
    #print "file: ", x
    ret = gc.action(x)
    fo.write(x+'\n')
    fo.write(str(ret)+'\n\n')
  fo.close()
  raw_input('done')
